package com.shrfid.rfidsdk.tag.hf;


import android.util.Log;

import com.shrfid.module_base.entity.TagEntity;
import com.shrfid.module_base.util.ByteUtils;
import com.shrfid.rfidsdk.tag.base.BaseResponseData;
import com.shrfid.rfidsdk.tag.base.BaseResponseFrame;
import com.shrfid.rfidsdk.uitls.ReadTagUtils;

import java.util.ArrayList;
import java.util.List;


public class HFInventoryResponse extends BaseResponseData {

    @Override
    public void parseFrame(BaseResponseFrame frame) {

        setRollCode(frame.getRollCode());

        if (frame.getLen() == 7) {
            //盘点结束帧
            //Log.d("READERSDK", "parse data break");
            if (frame.getStatus() == 0x00) {
                setComplete(true);
            } else {
                //错误码
                setData(new ArrayList<TagEntity>());
            }
        } else {
            byte[] params = frame.getParams();
            List<TagEntity> data = getData();
            if (data == null) {//数据为空,创建list
                data = new ArrayList<>();
            }
            if (params != null && params.length >= 10) {
                byte[] uid = new byte[8];
                System.arraycopy(params, 0, uid, 0, 8);
                int blockSize = 4;//params[8]+1
                int blockNum = params[9];//读到块的数量
                byte[] block = new byte[blockSize * blockNum];
                int startPosition = 11;
                int desPosition = 0;
                for (int i = 0; i < blockNum; i++) {
                    System.arraycopy(params, startPosition, block, desPosition, 4);
                    startPosition += 5;
                    desPosition += 4;
                }
                String tagEntityUid = ByteUtils.bytesToHexString(uid);
                String bookNo = ReadTagUtils.parse15693No(block);
                boolean isExist=false;
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getUid().equals(tagEntityUid))
                    {
                        isExist=true;
                        break;
                    }
                }
                if (!isExist) {
                    TagEntity tagEntity = new TagEntity(tagEntityUid, tagEntityUid, bookNo);
                    data.add(tagEntity);
                }
            }
            setData(data);
        }
    }
}
